package shiro.sso.chapter01.Filter;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;


//@WebFilter(filterName = "test", urlPatterns = "/*")
public class RequestFilter implements Filter {


    @Override
    public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request1 =((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
//        System.out.println(SecurityUtils.getSubject().isAuthenticated());
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        Enumeration<String> en = request.getParameterNames();
        Map<String, Object> extraParams = new HashMap<String, Object>();
        while (en.hasMoreElements()) {
            String key = en.nextElement();
            String[] arr = request.getParameterValues(key);
            String value = "";
            if (arr != null && arr.length > 0) {
                value = arr[0] + "_change";
            }
//            System.out.println(key+"解密后："+value);
            extraParams.put(key, value);
        }

        //利用原始的request对象创建自己扩展的request对象并添加自定义参数
        RequestWrapper requestParameterWrapper =new RequestWrapper(request);
        requestParameterWrapper.addParameter("age", 151);
        requestParameterWrapper.addParameter("pagecount" , 12);
        requestParameterWrapper.addParameters(extraParams);
        filterChain.doFilter(requestParameterWrapper, servletResponse);

    }
}
